package com.yb.framework.core.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
	
	public static final String yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
	
	public static String getNow() {
		return new SimpleDateFormat(yyyyMMddHHmmss).format(new Date(System.currentTimeMillis()));
	}
	
	/**
	 * Date转String
	 */
	public static String date2String(Date date) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.yyyyMMddHHmmss);
		String strDate = "";
		try {
			strDate = sdf.format(date);
		} catch (Exception e) {
    		System.out.println("Date 转 String 类型失败: " + e);
			return null;
		}
		return strDate;
	}
	
	public static String date2String(Date date, String format) {
		if (date == null) {
			return null;
		}
		if (format == null || format.equals("")) {
			format = DateUtil.yyyyMMddHHmmss;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String strDate = "";
		try {
			strDate = sdf.format(date);
		} catch (Exception e) {
    		System.out.println("Date 转 String 类型失败: " + e);
			return null;
		}
		return strDate;
	}
	
	/**
	 * String转Date
	 */
	public static Date string2Date(String strDate) {
		if (strDate == null || strDate.equals("")) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.yyyyMMddHHmmss);
		Date date = null;
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			System.out.println("String 转 Date 类型失败: " + e);
			return null;
		}
		return date;
	}
	
	public static Date string2Date(String strDate, String format) {
		if (strDate == null || strDate.equals("")) {
			return null;
		}
		if (format == null || format.equals("")) {
			format = DateUtil.yyyyMMddHHmmss;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(strDate);
		} catch (ParseException e) {
			System.out.println("String 转 Date 类型失败: " + e);
			return null;
		}
		return date;
	}
}
